package com.jiazhong.example.project.bookstore.front.listener;

import com.alibaba.fastjson.JSONArray;
import com.jiazhong.example.project.bookstore.commons.bean.RocketMQOrder;
import com.jiazhong.example.project.bookstore.front.service.impl.ShoppingCartServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;

// 购物车消费者
@Slf4j
@Component
//@RocketMQMessageListener(consumerGroup = "order_success_5", topic = "Order", selectorExpression = "transaction", messageModel = MessageModel.BROADCASTING)
public class OrderSuccessShoppingCartListener implements RocketMQListener<String> {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onMessage(String s) {
        log.info("开始执行修改购物车操作");
        RocketMQOrder rocketMQOrder = JSONArray.parseObject(s, RocketMQOrder.class);
        log.info("购物车，rocketMQOrder:{}", rocketMQOrder);
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();
        rocketMQOrder.getOrderItemList().forEach(item -> forHash.delete(ShoppingCartServiceImpl.SHOPPING_CART_PREFIX + rocketMQOrder.getUserId(), item.getBookId()));
        // 有没有更优秀的解决方案
        Set<String> keys = stringRedisTemplate.keys("findCartByUserId*");
        log.info("所有的key:{}", keys);
        keys.forEach(item -> {
            log.info("删除:{}", item);
            stringRedisTemplate.delete(item);
        });

    }
}
